#!/bin/bash
# Jenkins凭据配置脚本
# 用于自动配置Jenkins中的凭据信息

set -e

echo "🔐 配置Jenkins凭据..."

# Jenkins CLI路径（需要根据实际情况修改）
JENKINS_URL="http://jenkins.internal:8080"
JENKINS_CLI="java -jar jenkins-cli.jar -s $JENKINS_URL"

# 检查Jenkins CLI是否可用
if ! command -v java &> /dev/null; then
    echo "❌ Java未安装，无法使用Jenkins CLI"
    exit 1
fi

# 下载Jenkins CLI（如果不存在）
if [ ! -f "jenkins-cli.jar" ]; then
    echo "📥 下载Jenkins CLI..."
    curl -O "$JENKINS_URL/jnlpJars/jenkins-cli.jar"
fi

# 函数：创建用户名密码凭据
create_username_password_credentials() {
    local id=$1
    local username=$2
    local password=$3
    local description=$4
    
    echo "创建用户名密码凭据: $id"
    
    cat <<EOF | $JENKINS_CLI create-credentials-by-xml system::system::jenkins _
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
    <scope>GLOBAL</scope>
    <id>$id</id>
    <description>$description</description>
    <username>$username</username>
    <password>$password</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
EOF
}

# 函数：创建密钥文本凭据
create_secret_text_credentials() {
    local id=$1
    local secret=$2
    local description=$3
    
    echo "创建密钥文本凭据: $id"
    
    cat <<EOF | $JENKINS_CLI create-credentials-by-xml system::system::jenkins _
<org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl>
    <scope>GLOBAL</scope>
    <id>$id</id>
    <description>$description</description>
    <secret>$secret</secret>
</org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl>
EOF
}

# 函数：创建SSH密钥凭据
create_ssh_credentials() {
    local id=$1
    local username=$2
    local private_key_path=$3
    local description=$4
    
    echo "创建SSH密钥凭据: $id"
    
    if [ ! -f "$private_key_path" ]; then
        echo "❌ SSH私钥文件不存在: $private_key_path"
        return 1
    fi
    
    local private_key=$(cat "$private_key_path" | base64 -w 0)
    
    cat <<EOF | $JENKINS_CLI create-credentials-by-xml system::system::jenkins _
<com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey>
    <scope>GLOBAL</scope>
    <id>$id</id>
    <description>$description</description>
    <username>$username</username>
    <privateKeySource class="com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey\$DirectEntryPrivateKeySource">
        <privateKey>$(echo "$private_key" | base64 -d)</privateKey>
    </privateKeySource>
</com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey>
EOF
}

echo "📋 开始配置凭据..."

# ===================================
# 数据库凭据
# ===================================
echo "🗄️ 配置数据库凭据..."

# 开发环境数据库
create_username_password_credentials \
    "dev-database-credentials" \
    "${DEV_DB_USER:-deviceuser}" \
    "${DEV_DB_PASSWORD:-devicepass}" \
    "开发环境数据库凭据"

# 生产环境数据库
create_username_password_credentials \
    "prod-database-credentials" \
    "${PROD_DB_USER:-deviceuser}" \
    "${PROD_DB_PASSWORD:-change-this-password}" \
    "生产环境数据库凭据"

# ===================================
# Redis凭据
# ===================================
echo "🔴 配置Redis凭据..."

create_secret_text_credentials \
    "redis-password" \
    "${REDIS_PASSWORD:-change-this-redis-password}" \
    "Redis密码"

# ===================================
# Docker Registry凭据
# ===================================
echo "🐳 配置Docker Registry凭据..."

create_username_password_credentials \
    "docker-registry-credentials" \
    "${DOCKER_REGISTRY_USER:-your-docker-user}" \
    "${DOCKER_REGISTRY_PASSWORD:-your-docker-password}" \
    "Docker Registry凭据"

# ===================================
# Git/GitHub凭据
# ===================================
echo "📂 配置Git凭据..."

# GitHub Personal Access Token
create_secret_text_credentials \
    "github-token" \
    "${GITHUB_TOKEN:-your-github-token}" \
    "GitHub访问令牌"

# GitHub用户名密码
create_username_password_credentials \
    "github-credentials" \
    "${GITHUB_USER:-your-github-user}" \
    "${GITHUB_TOKEN:-your-github-token}" \
    "GitHub凭据"

# SSH密钥（如果存在）
if [ -f ~/.ssh/id_rsa ]; then
    create_ssh_credentials \
        "github-ssh-key" \
        "git" \
        "~/.ssh/id_rsa" \
        "GitHub SSH密钥"
fi

# ===================================
# JWT密钥
# ===================================
echo "🔑 配置JWT密钥..."

create_secret_text_credentials \
    "jwt-secret-key" \
    "${JWT_SECRET_KEY:-$(openssl rand -base64 32)}" \
    "JWT密钥"

# ===================================
# 邮件凭据
# ===================================
echo "📧 配置邮件凭据..."

create_username_password_credentials \
    "email-credentials" \
    "${SMTP_USERNAME:-noreply@company.com}" \
    "${SMTP_PASSWORD:-your-email-password}" \
    "SMTP邮件凭据"

# ===================================
# Kubernetes凭据
# ===================================
echo "☸️ 配置Kubernetes凭据..."

# Kubeconfig文件
if [ -f ~/.kube/config ]; then
    create_secret_text_credentials \
        "kubeconfig" \
        "$(cat ~/.kube/config | base64 -w 0)" \
        "Kubernetes配置文件"
fi

# ===================================
# 第三方服务凭据
# ===================================
echo "🔗 配置第三方服务凭据..."

# SonarQube Token
if [ -n "$SONARQUBE_TOKEN" ]; then
    create_secret_text_credentials \
        "sonarqube-token" \
        "$SONARQUBE_TOKEN" \
        "SonarQube访问令牌"
fi

# Slack Webhook
if [ -n "$SLACK_WEBHOOK_URL" ]; then
    create_secret_text_credentials \
        "slack-webhook" \
        "$SLACK_WEBHOOK_URL" \
        "Slack Webhook URL"
fi

# AWS访问凭据
if [ -n "$AWS_ACCESS_KEY_ID" ]; then
    create_username_password_credentials \
        "aws-credentials" \
        "$AWS_ACCESS_KEY_ID" \
        "$AWS_SECRET_ACCESS_KEY" \
        "AWS访问凭据"
fi

echo "✅ 凭据配置完成！"

# 验证凭据
echo "🔍 验证凭据配置..."
$JENKINS_CLI list-credentials system::system::jenkins

echo ""
echo "📝 凭据配置总结："
echo "  ✅ 数据库凭据已配置"
echo "  ✅ Docker Registry凭据已配置"
echo "  ✅ Git/GitHub凭据已配置"
echo "  ✅ JWT密钥已配置"
echo "  ✅ 邮件凭据已配置"
echo "  ✅ 第三方服务凭据已配置"
echo ""
echo "🚀 现在可以开始使用Jenkins Pipeline了！"